﻿using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEditor;
using UnityEngine;

namespace Nirvana
{
    /// <summary>
    /// 用于保存各种应用软件的路径：LuaCheck.exe 
    /// </summary>
    public sealed class ApplicationPathBind
    {
        private string appname;
        private string key;
        private string[] values;
        private string appPath;

        public ApplicationPathBind(string key,string appname,string[] values)
        {
            this.key = key;
            this.appname = appname;
            this.values = values;
        }

        public string GetAppPath()
        {
            if(string.IsNullOrEmpty(this.appPath) && EditorPrefs.HasKey(this.key))
            {
                string filepath = EditorPrefs.GetString(this.key);
                if (File.Exists(filepath))
                {
                    this.appPath = filepath;
                }
                else
                {
                    EditorPrefs.DeleteKey(this.key);
                }
            }
            if (string.IsNullOrEmpty(this.appPath))
            {
                SearchAppPath();
            }
            return this.appPath;
        }

        public void Show()
        {
            string path = this.GetAppPath();
            string appFriendlyName = AssemblyTool.GetAppFriendlyName(path);
            string name = "";
            if(this.appname == appFriendlyName)
            {
                name = string.Format("{0}:", this.appname);
            }
            else
            {
                name = string.Format("{0}: {1}", appname, appFriendlyName);
            }

            EditorGUILayout.BeginHorizontal();
            EditorGUILayout.LabelField(name,GUILayout.Width(225f));
            if (GUILayout.Button("Search..."))
            {
                this.SearchAppPath();
            }
            if (GUILayout.Button("Browse..."))
            {
                string p = EditorUtility.OpenFilePanel("Browse for application", string.Empty, ".exe");
                if (p.Length != 0) SetAppPath(p);
            }
            EditorGUILayout.EndHorizontal();
            EditorGUILayout.LabelField(path);
        }

        private void SearchAppPath()
        {
            foreach(var t in this.values)
            {
                if (File.Exists(t))
                {
                    this.appPath = t;
                    EditorPrefs.SetString(this.key, t);
                }
            }
        }

        private void SetAppPath(string path)
        {
            if (!File.Exists(path)) return;
            this.appPath = path;
            EditorPrefs.SetString(this.key, path);
        }
    }
}

